var localStorage = window.localStorage;
var courseNumber = localStorage.CourseNumber;
var is_tutor = localStorage.is_tutor;
var uId = localStorage.UNumber;
var wsMark = col = row = 0;
var websocket = null;
var seat = '';
var selectSeat = ' ';
var preRecord = 0;
console.log('keshihao: '+ courseNumber);

if ('WebSocket' in window) {
    websocket = new WebSocket('ws://120.79.245.60:8080/eooker/webSocket/' + courseNumber + '/' + uId);
} else {
    // alert('当前浏览器 不支持WebSocket')
}
// 显示上面信息
intI();

//公用弹出层
function popu(content){
    layer.open({
        content: content
        ,skin: 'msg'
        ,time: 3
    });
}
//接收到消息的回调方法，此处添加处理接收消息方法，当前是将接收到的信息显示在网页上
websocket.onmessage = function(event) {
    // console.log('接受到:' + event.data);
    var data = event.data;
    wsMark += 1;
    if(wsMark ==1){
        seatingTable(strTranlistTwo(data));
        drafting();
        $('.tip-border3').css('display','block');
        $('.hNumber-Tip').html('房间号：' + courseNumber);
        $('.tip-border3-after').css('top','1330px');
    }
    var reg1 = /^onlineCount.{1,6}$/;
    var reg2 = /^\d{1,3}-\d{1,3}$/;
    var reg3 =  /^maxTotal.{1,6}$/;//最大在线量
    var reg4 = /^-.{3,8}$/;
    var reg5 = /^S.{3,6}$/;
    if(reg1.test(data)){
        var mar = data.split(':')[1] - '0' - 1;
        $('.selectNumber').html(mar);
    }
    if(reg3.test(data)){
        $('.tip-border3').css('display','block');
        $('.tip-border3-after').css('top','1160px');
        var mar = data.split(':')[1] - '0' - 1;
        $('.maxNumber').html(mar);
    }

    if(reg4.test(data)){

        var mar = data.substring(1);
        // alert('mar == ' + mar + '   selectSeat == ' + selectSeat);
        if(mar == selectSeat);
        else {
            var str = mar.split('-');
            var i = (str[0] - '0') * col + (str[1]-'0') + 1;
            var tool = '[for=' + "'" + 'seat-' + i + "'" + ']';
            // alert(str[0] + '    ' + str[1]);
            $(tool).css('background-position','0 0');

        }

    }
    if(reg5.test(data)){
        var url = 'http://120.79.245.60:8080/eooker/a/sys/userAPI/scanCode/' + uId;
        $.ajax({
            url: url,
            type: 'Get',
            dataType: 'JSON',
            crossDomain: true,
            success: function(data){
                console.log(data)
                $('#qrCode').css('display','inline-block');
                $('#code').qrcode({
                    render: "table",
                    width: 500,
                    height: 500,
                    text: data.resultMap.scanCode
                });
                $('.btn-qrCode').css('display','block')
            },
            error: function () {
                mesLay("生成二维码失败~");
            }
        });

        var tool = data.substring(1);
        var mar = tool.split('-');
        var r = mar[0] - '0' + 1;
        var c = mar[1] - '0' + 1;
        var str =  r + '行 ' + c + '列';
        var mySeat = seat.split('-');
        var myR = mySeat[0] - '0' + 1;
        var myC = mySeat[1] - '0' + 1;
        console.log('r:  ' + r+' c:  '+c+'  myR:  ' + myR+'  myC:  ' + myC);
        $('.tip-Inf').css('display','block');
        $('.tip-seat').html(str);
        if(c > myC)str = '他/她在你的右';
        else if( c < myC)str = '他/她在你的左';
        else str = '他/她在你的正';
        if(r > myR)str += '后方';
        else if(r < myR)str +='前方';
        else str += '边(跟你坐在同一排)';
        $('.tip-direction').html(str);
    }
    if(reg2.test(data)){
        var mar = data.split('-');
        var i = (mar[0] - '0') * col + (mar[1]-'0') + 1;
        // alert('第几个位置  ' + i +'   0: '  + mar[0] + '  1: ' + mar[1]);
        if(seat == data){ //自己选的
            selectSeat = seat;
            if(preRecord !=0){
                var tool = '[for=' + "'" + 'seat-' + preRecord + "'" + ']';
                $(tool).css('background-position','0 0');
            }//之前选的变回白
            var tool = '[for=' + "'" + 'seat-' + i + "'" + ']';
            if(is_tutor == 0)$(tool).css('background-position','0 -60px');//新选的变绿
           preRecord = i;
        }
        else {
            var tool = '#seat-' + i ;
            $(tool).parent().prop('class','selected');
            if($(tool).parent().attr('class') == 'selected'){
                var tool = '[for=' + "'" + 'seat-' + i + "'" + ']';
                $(tool).css('background-position','0 -120px');
            }
        }
    }

}
function strTranlistTwo(str) {
    var str1 = str.substring(2, str.length-2);
    var str2 = str1.split('],[');
    str2[str2.length-1].substring(0, str.length-2);
    str2[0].substring(1);
    row = str2.length;
    col = Math.ceil(str2[5].length/2);
    var arr=new Array();
    for( let i = 0; i < row; i++) {
        arr[i] = new Array();
        var str3 = str2[i].split(',');
        for (let j = 0; j < str3.length; j++) {
            arr[i][j] = str3[j] - '0';
        }
    }
    return arr;
}

// 初始化课室~桌子的监听
function seatingTable(seatList){

    var html='';
    var mySelect = '';
    html+='<ul class="touchs" id="touchs"><div class="screen">课室屏幕</div>';
    var listOne = changeList(seatList);

    for(var i=1; i < listOne.length; i++){
        var selected = (listOne[i]==1 ? 'selected' : '');
        html+='<li class="'+selected+'">';
        html+='<input type="checkbox" name="'+i+'" id="seat-'+i+'" />';
        html+='<label for="seat-'+i+'"></label>';
        html+='</li>';
        if(listOne[i] == 2) {
            mySelect = '[for=' + "'" + 'seat-' + i + "'" + ']';
            preRecord = i;
        }

    }

    html+='<div class="the_best"></div><div class="crossnum" id="crossnum"></div></ul>';
    $('#seats').html(html);
    $(mySelect).css('background-position','0 -60px');
    // 座位表宽度初始化
    $(".touchs").width(col * 70);

    $('.selected').children('input').attr({'disabled':'disabled','checked':'checked'});

    // 判定选了多少个座位默认1,还有坐标的获取
    $('.seats li input').on('click',function(){
        $(this).prop("checked",false);

        var checklen = $('.seats li').not('.selected').children('input:checked').length;
        // console.log(checklen);
        if(checklen>1){
            popu('最多只能选择1个座位');
            return false;
        }
        // alert('name='+this.name+' / id='+this.id);
        var local = parseInt(this.name);
        // x列y行
        var x = local % col;
        if( x ==0 )x = 15;
        var y = Math.ceil(local / col);
        var c = x - 1;
        var r = y -1;
        // console.log(typeof y);
        // console.log(local);
        // console.log(y + '行' + x + '列');
        if(is_tutor == '0')websocket.send(r + '-' + c);
        seat = r + '-' + c;
        // console.log(y - 1 + '-' + x - 1);
        // var inf = this.next().className;
        // alert(inf);
    });
    $('#cancel').on('click',function(){

    });
    $('.btn-qrCode').on('click',function(){
        self.location = 'qr.html'
    });
    $('#end').on('click',function(){
        var inf =   $('#end').html();
        if(inf == '选座结束') {
            var url = 'http://120.79.245.60:8080/eooker/a/sys/userAPI/finishSelect/' + courseNumber;
            console.log(url);
            $.ajax({
                url: url,
                type: 'Get',
                dataType: 'JSON',
                crossDomain: true,
                success: function (data) {
                    if(data.message == 'success') {
                        popu("选座已结束");
                        $('#end').html('再次验证');
                    }
                },
                error: function () {
                    popu("服务器正在抢修，暂时验证不了");
                }
            });
        }
        else {

        }
    });
    $('#qrCode').on('click',function(){
        var qrcode = $('.qrcode-div');
        if(qrcode.css('height') == '0px'){
            qrcode.css('height','560');
            qrcode.css('width','90%');
        }
        else {
            qrcode.css('height','0px');
            qrcode.css('width','0px');
        }
    });


    // 判断有多少行 给出左边的提示
    var num='';
    num+='<ul>';
    for(var i=1; i<=row; i++){
        num+='<li>'+i+'</li>';
    }
    html+='</ul>';
    $('#num').html(num);

    var crossnum='';
    crossnum+='<ul>';
    for(var j=1; j<=col; j++){
        crossnum+='<li>'+j+'</li>';
    }
    html+='</ul>';
    $('#crossnum').html(crossnum);

}
//-------------------------------------seatingTable函数结束-----------------------------------------

function intI() {
    var url = 'http://120.79.245.60:8080/eooker/a/sys/userAPI/roomInfo/' + courseNumber;
    $.ajax({
        url: url,
        type: 'Get',
        dataType: 'JSON',
        crossDomain: true,
        success: function(data){
            if(is_tutor == 0){
                $('#stuMark1').css('display','block');
                $('#stuMark2').css('display','block');
                $('#stuMark3').css('display','block');
                $('.seat_head').css('display','block');
                $('#cancel').css('display','block');
                $('#lct').html(data.resultMap.location);
                $('#teacher').html('导师：' + data.resultMap.tutorName);
                $('#csName').html(data.resultMap.courseName);
            }
            else if(is_tutor == 1){
                $('#teaMark1').css('display','block');
                $('#teaMark2').css('display','block');
                $('#teaMark3').css('display','block');
                $('.maxTotal').css('display','block');
                $('#end').css('display','block');
                $('.t3').css('padding-left', '20px');
            }

        },
        error: function () {
            mesLay("帐号不存在或帐号密码输入有误请重新输入");
        }
    });
}


// 2→1
function changeList(listTwo) {
    var row = listTwo.length;
    var col = listTwo[3].length;
    console.log(listTwo);
    var listOne = [];
    var index = 1;
        var i = j = 0;
    for( i = 0; i < row; i++)
    {
        for( j = 0; j < col; j++)
        {
            listOne[index++] = listTwo[i][j];
        }
    }
    return listOne;
}



//连接发生错误的回调方法
websocket.onerror = function() {
    // alert("发生错误")
};

//连接成功建立的回调方法
websocket.onopen = function() {
    console.log("连接服务器成功!")
}


//连接关闭的回调方法
websocket.onclose = function() {
    popu("ws不行啊兄弟")
    // popu('您的账号在另一台手机登陆');
    // window.setTimeout(goToHome,3000);
}

//将消息显示在网页上，如果不需要显示在网页上，则不调用该方法
function setMessageInnerHTML(innerHTML) {
    document.getElementById('message').innerHTML += innerHTML + '<br/>';
}


//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function() {
    closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket() {
    websocket.close();
}
// }
function goToHome(){
    self.location = 'login.html';
}

// ***********图片上传**********
$('#fileUpload0').change(function() {
    uploadImg(this);
});
function uploadImg(element){
    var file = element.files[0];
    var $elemt=$(element);
    var $parent = $elemt.parent();
    var imgFileSize = file.size;
    var loadingImgSrc='/images/global/loading.gif';
    if(imgFileSize > 10*1024*1024) {
        alert(ci18n.imgTooLarge);
    } else {
        var uploadComplete=function(evt){
            var resJson=JSON.parse(evt.target.responseText);
            if(resJson.fileurl){
                $parent.find('img').attr('src',resJson.fileurl);
                uploadImgUrls['a'+$elemt.parent().parent().index()]=resJson.fileurl;
                $parent.find('.delImg').show();
                $parent.parent('li').next().show();
            }
        };
        var uploadFailed=function(evt){
            alert('Net error.');
        };
        var fd = new FormData();
        fd.append('upfile',file);
        var xhr = new XMLHttpRequest();
        xhr.addEventListener('load', uploadComplete, false);
        xhr.addEventListener('error', uploadFailed, false);
        xhr.open('POST', '/activity/group-upload');
        $parent.append('<img src="'+loadingImgSrc+'">');
        xhr.send(fd);
    }
    element.value = '';
}
$('.delImg').click(function() {
    var $self=$(this);
    var $parent = $self.parent();
    delete uploadImgUrls['a'+$self.parent().parent().index()];
    $parent.find('img').remove('');
    $self.hide();
    $parent.parent('li').next().hide();
});


// <!---拖拽js--->

function drafting(){
    var flag = false;
    var cur = {
        x:0,
        y:0
    }
    var nx,ny,dx,dy,x,y ;
    function down(){
        flag = true;
        var touch ;
        if(event.touches){
            touch = event.touches[0];
        }else {
            touch = event;
        }
        cur.x = touch.clientX;
        cur.y = touch.clientY;
        dx = div2.offsetLeft;
        dy = div2.offsetTop;
    }
    function move(){
        if(flag){
            var touch ;
            if(event.touches){
                touch = event.touches[0];
            }else {
                touch = event;
            }
            nx = touch.clientX - cur.x;
            ny = touch.clientY - cur.y;
            x = dx+nx;
            y = dy+ny;
            div2.style.left = x+"px";
            //div2.style.top = y +"px";


            //阻止页面的滑动默认事件
            document.addEventListener("touchmove",function(){
                //event.preventDefault();
            },false);
        }
    }
    //鼠标释放时候的函数
    function end(){
        flag = false;
    }
    var div2 = document.getElementById("touchs");
    div2.addEventListener("mousedown",function(){
        down();
    },false);
    div2.addEventListener("touchstart",function(){
        down();
    },false)
    div2.addEventListener("mousemove",function(){
        move();
    },false);
    div2.addEventListener("touchmove",function(){
        move();
    },false)
    document.body.addEventListener("mouseup",function(){
        end();
    },false);
    div2.addEventListener("touchend",function(){
        end();
    },false);

}